package com.childenglish.validation;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Pattern;

/**
 * 可选模式匹配验证器
 */
public class OptionalPatternValidator implements ConstraintValidator<OptionalPattern, String> {
    
    private Pattern pattern;
    
    @Override
    public void initialize(OptionalPattern constraintAnnotation) {
        int flags = 0;
        for (javax.validation.constraints.Pattern.Flag flag : constraintAnnotation.flags()) {
            flags |= flag.getValue();
        }
        this.pattern = Pattern.compile(constraintAnnotation.regexp(), flags);
    }
    
    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        // 如果值为空或null，则跳过验证
        if (value == null || value.trim().isEmpty()) {
            return true;
        }
        return pattern.matcher(value).matches();
    }
}

